package com.zzb.ws;


import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zzb.pojo.Message;
import com.zzb.pojo.ResultMessage;
import com.zzb.pojo.User;
import com.zzb.utils.MessageUtils;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpSession;
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

//configurator = GetHttpSessionConfigurator.class
//需要声明否则this.httpSession会为null，报空指针异常
/*
        //获取httpsession对象
        this.httpSession = (HttpSession)config.getUserProperties().get(HttpSession.class.getName());
        //从httpSession获取用户名
        User user = (User) httpSession.getAttribute("loginUser");
 */
@ServerEndpoint(value = "/chat", configurator = GetHttpSessionConfigurator.class)
@Component
public class ChatEndpoint {

    //用来存储每一个客户端对应的ChatEndpoint对象   并发ConcurrentHashMap<>()
    private static Map<String, ChatEndpoint> onlineUsers = new ConcurrentHashMap<>();

    //声明websocket session对象，用来发送消息给指定的客户端
    private Session session;

    //httpSession存储了登陆的user对象
    private HttpSession httpSession;

    /**
     * 连接时触发
     * @param session
     * @param config
     */
    @OnOpen
    public void onOpen(Session session, EndpointConfig config){
        this.session = session;
        //获取httpsession对象
        this.httpSession = (HttpSession)config.getUserProperties().get(HttpSession.class.getName());
        //从httpSession获取用户名
        User user = (User) httpSession.getAttribute("loginUser");
        String username = user.getUsername();

        //将当前对象存储到容器中
        onlineUsers.put(username,this);

        //将当前在线用户推送给所有客户端
        //1 获取消息
        String res = MessageUtils.getMessage(true, null, getNames());
        //2 推送系统消息
        broadcastAllUsers(res);
    }

    //广播系统消息
    private void broadcastAllUsers(String message){
        try {
            for (String s : onlineUsers.keySet()) {
                ChatEndpoint chatEndpoint = onlineUsers.get(s);
                chatEndpoint.session.getBasicRemote().sendText(message);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private Set<String> getNames(){
        return onlineUsers.keySet();
    }



    /**
     * 接收 客户端--->服务端 的消息
     * @param message
     * @param session
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        try {
            //将json字符串转换为实体类对象
            ObjectMapper mapper = new ObjectMapper();
            Message msg = mapper.readValue(message, Message.class);
            //获取toName与消息
            String toName = msg.getToName();
            String data = msg.getMessage();
            //获取fromName
            String fromName = ((User)httpSession.getAttribute("loginUser")).getUsername();
            //封装
            String res = MessageUtils.getMessage(false, fromName, data);
            //向toName发送消息
            onlineUsers.get(toName).session.getBasicRemote().sendText(res);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @OnError
    public void onError(Session session, Throwable throwable) {

    }

    @OnClose
    public void onClose(Session session, CloseReason closeReason) {

    }


}
